package com.ljf.common.web;

import com.ljf.common.service.INoDBBasisService;
import org.springframework.context.ApplicationContext;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;

/**
 * 基础控制器-无数据表
 *
 * @author LJF
 * @since 2024-10-01
 */
public class NoDBBasisController<S extends INoDBBasisService> {

    @Resource
    private ApplicationContext applicationContext;

    protected S service;

    private Class<S> serviceClass;

    @PostConstruct
    private void init() {
        this.getService();
    }

    /**
     * 获取服务对象
     *
     * @return
     */
    private S getService() {
        if (this.service == null) {
            Class<S> sampleObjectCallBack = this.getSuperClassGenricType(0);
            this.service = this.applicationContext.getBean(sampleObjectCallBack);
        }
        return this.service;
    }

    /**
     * 获取服务Bean类型
     *
     * @param index
     * @return
     */
    private Class<S> getSuperClassGenricType(int index) {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        int count = type.getActualTypeArguments().length;
        if (count > 0) {
            this.serviceClass = (Class) type.getActualTypeArguments()[index];
        }
        return this.serviceClass;
    }

}
